package com.bw.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.ResponseResult;
import com.bw.common.sms.SendSms;
import com.bw.goods.entity.SysUser;
import com.bw.goods.mapper.SysUserMapper;
import com.bw.goods.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xingjinning
 * @since 2020-07-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult sendCode(String phone) {
        ResponseResult result = ResponseResult.SUCCESS();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        SysUser sysUser = userMapper.selectOne(queryWrapper);
        if(null==sysUser){
            result.setSuccess(false);
            result.setMessage("用户不存在");
            return result;
        }
        Boolean b = redisTemplate.boundValueOps("S:" + phone).setIfAbsent("y", 1, TimeUnit.MINUTES);
        if(!b){
            result.setSuccess(false);
            result.setMessage("发送频繁");
            return result;
        }
        String num = redisTemplate.boundValueOps("P:" + phone).get();
        if(null!=num){
            if(Integer.parseInt(num)>10){
                result.setSuccess(false);
                result.setMessage("今日操作已达上限");
                return result;
            }
        }else{
            redisTemplate.boundValueOps("P:"+phone).expire(1,TimeUnit.DAYS);
        }
        redisTemplate.boundValueOps("P:"+phone).increment();
        int code= (int) (Math.random()*1000000);
        redisTemplate.boundValueOps("Y:"+phone).set(String.valueOf(code),90,TimeUnit.SECONDS);
        System.out.println("验证码"+code);
//        SendSms.send(phone,String.valueOf(code));
        return result;
    }
}
